<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\GeneralException;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Pay\Pay;
use App\Http\Requests\Admin\Service\ServiceCalculation;
use App\Models\Service;
use App\Models\StationBills;
use App\Repositories\UserLogRepository;
use App\Repositories\ServiceBillRepository;
use App\Http\Requests\Admin\ServiceBill\QueryResource;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class ServiceBillController extends Controller
{
    protected $serviceBillRepository;
    protected $userLogRepository;

    /**
     * AdminController constructor.
     * @param ServiceBillRepository $serviceBillRepository
     * @param UserLogRepository $userLogRepository
     */
    public function __construct(
        ServiceBillRepository $serviceBillRepository,
        UserLogRepository $userLogRepository
    )
    {
        $this->serviceBillRepository = $serviceBillRepository;
        $this->userLogRepository = $userLogRepository;
    }

    /**
     * 获取站点账单
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(QueryResource $request)
    {
        $limit = $request->get('paginate', 15);
        $name = $request->get('service_name', false);
        $created_at = $request->get('month', false);
        if ($name === null) {
            $name = false;
        }
        if ($created_at === null) {
            $created_at = false;
        }
        $admins = $this->serviceBillRepository->getStationBills($name, $created_at, $limit);
        return success($admins);
    }

    /**
     * 结算
     *
     * Date: 2018/05/18
     * @author Tenny
     * @param ServiceCalculation $request
     * @param StationBills $settlement
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function calculation(ServiceCalculation $request, StationBills $settlement)
    {
        //先查询是否支付
        if (optional($settlement)->status === null || optional($settlement)->status != 0) {
            return failed('该账单已经支付过了', 403);
        }
        //支付操作
        $service = Service::query()->where('id', '=', $settlement->service_id)->first();
        if (optional($service)->bank_card === null || optional($service)->bank_card == false) {
            return failed('该站点没有支付宝账号', 403);
        }
        $id = date('YmdHis');
        $payee_account = $service->bank_card;
        $amount = round($settlement->total_income, 2);
        $pay = new Pay();
        DB::beginTransaction();
        try {
            $res = $pay->transfer($id, $payee_account, $amount);
            //支付成功改变状态
            if (array_key_exists('alipay_fund_trans_toaccount_transfer_response', $res) && array_key_exists('code', $res['alipay_fund_trans_toaccount_transfer_response']) && $res['alipay_fund_trans_toaccount_transfer_response']['code'] == 1000) {
                $settlement->status = 1;
                $settlement->number = $res;
                $settlement->save();
            } else {
                //支付失败 记录日志
                return failed('结算失败！', 500);
            }
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $admin = Auth::guard('admin')->user();
        $uid = $admin->id;
        $service_id = $settlement->service_id;
        $name = $admin->name;
        $operation = $admin->name . '结算了账单[' . $settlement->id . ']';
        $history = $actuality = null;
        $order_id = 0;//非订单
        $ip = $request->getClientIp();
        $type = 2;//共派管理员
        $this->userLogRepository->myLog($uid, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        return updated([], '结算成功！');
    }
}
